import Vue from 'vue';
//金额过滤
Vue.filter('money', function(val) {
	if (val) {
		let value = Math.round(parseFloat(val) * 100) / 100;
		let valMoney = value.toString().split(".");
		if (valMoney.length == 1) {
			value = value.toString() + ".00";
			return value;
		}
		if (valMoney.length > 1) {
			if (valMoney[1].length < 2) {
				value = value.toString() + "0";
			}
			return value;
		}
		return value;
	} else {
		return "0.00";
	}
});
//手机号中间4位为*
Vue.filter('phone', function(val) {
	var tel = val;
	tel = "" + tel;
	var telShort = tel.replace(tel.substring(3, 7), "****")
	return telShort
})
//获取系统信息、判断ipX安全距离
export const getTabbarHeight = function() {
	var systemInfo = uni.getSystemInfoSync()
	var data = {
		...systemInfo,
		tabbarH: 50, //tabbar高度--单位px
		tabbarPaddingB: 0, //tabbar底部安全距离高度--单位px
		device: systemInfo.system.indexOf('iOS') != -1 ? 'iOS' : 'Android', //苹果或者安卓设备
	}
	let modelArr = ['10,3', '10,6', 'X', 'XR', 'XS', '11', '12', '13', '14', '15', '16'];
	let model = systemInfo.model;
	model && modelArr.forEach(item => {
		//适配iphoneX以上的底部，给tabbar一定高度的padding-bottom
		if (model.indexOf(item) != -1 && (model.indexOf('iPhone') != -1 || model.indexOf('iphone') != -1)) {
			data.tabbarH = 70
			data.tabbarPaddingB = 20
		}
	})
	return data;
}

// 时间过滤
Vue.filter('chartDatetime', function(val, hasTime = false) {
	if (!val) {
		return ''
	}
	let t = new Date(typeof val === 'number' ? val : val.replace(/-/g, '/'))
	let cur = new Date()
	let tDate = new Date(formatTimestamp(t, 'yyyy/MM/dd') + ' 00:00:00').getTime()
	let curDate = new Date(formatTimestamp(cur, 'yyyy/MM/dd') + ' 00:00:00').getTime()
	let diff = curDate - tDate
	let oneDay = 24 * 60 * 60 * 1000

	// 格式化时间部分
	let tHours = ((t.getHours() % 12) || 12).toString().padStart(2, '0')
	let tMinutes = t.getMinutes().toString().padStart(2, '0')
	let tUnit = t.getHours() < 12 ? 'AM' : 'PM'
	let tTime = `${tHours}:${tMinutes} ${tUnit}`

	// 如果是同一天,只返回时间
	if (diff === 0) {
		return tTime
	}
	// 如果是前一天
	else if (diff === oneDay) {
		return '昨天' + (hasTime ? ` ${tTime}` : '')
	}
	// 如果是同一年
	else if (t.getFullYear() === cur.getFullYear()) {
		return formatTimestamp(t, 'MM-dd') + (hasTime ? ` ${tTime}` : '')
	}
	// 否则返回日期
	else {
		return formatTimestamp(t, 'yyyy-MM-dd') + (hasTime ? ` ${tTime}` : '')
	}
});

// 时间过滤
Vue.filter('com-datetime', function(val) {
	if (!val) {
		return ''
	}
	let t = new Date(typeof val === 'number' ? val : val.replace(/-/g, '/'))
	let cur = new Date()
	let tDate = new Date(formatTimestamp(t, 'yyyy/MM/dd') + ' 00:00:00').getTime()
	let curDate = new Date(formatTimestamp(cur, 'yyyy/MM/dd') + ' 00:00:00').getTime()
	let diff = curDate - tDate
	let oneDay = 24 * 60 * 60 * 1000

	// 如果是同一天,只返回时间
	if (diff === 0) {
		return formatTimestamp(t, 'hh:mm')
	}
	// 如果是前一天
	else if (diff === oneDay) {
		return `昨天 ${formatTimestamp(t, 'hh:mm')}`
	}
	// 如果是同一年
	else if (t.getFullYear() === cur.getFullYear()) {
		return formatTimestamp(t, 'MM-dd hh:mm')
	}
	// 否则返回日期
	else {
		return formatTimestamp(t, 'yyyy-MM-dd hh:mm')
	}
});

// 好友在线状态过滤
Vue.filter('chat-friend-status', function(val) {
	switch (val) {
		case 0:
			return '离线'
			break;
		case 1:
			return '在线'
			break;
		default:
			return '未知'
			break;
	}
});

// 格式化时间戳
function formatTimestamp(t, fmt = 'yyyy-MM-dd hh:mm:ss') {
	if (!t) {
		return ''
	}

	let ret;
	let time = new Date(t);
	const opt = {
		"y+": time.getFullYear().toString(), // 年
		"M+": (time.getMonth() + 1).toString(), // 月
		"d+": time.getDate().toString(), // 日
		"h+": time.getHours().toString(), // 时
		"m+": time.getMinutes().toString(), // 分
		"s+": time.getSeconds().toString() // 秒
		// 有其他格式化字符需求可以继续添加，必须转化成字符串
	};
	for (let k in opt) {
		ret = new RegExp("(" + k + ")").exec(fmt);
		if (ret) {
			fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
		};
	};
	return fmt;
}

//计算两点距离
export const commonDistance = function(lat1, lng1, lat2, lng2) {
	var f = ((lat1 + lat2) / 2) * Math.PI / 180.0;
	var g = ((lat1 - lat2) / 2) * Math.PI / 180.0;
	var l = ((lng1 - lng2) / 2) * Math.PI / 180.0;
	var sg = Math.sin(g);
	var sl = Math.sin(l);
	var sf = Math.sin(f);
	var s, c, w, r, d, h1, h2;
	var a = 6378137.0; //地球的直径
	var fl = 1 / 298.257;
	sg = sg * sg;
	sl = sl * sl;
	sf = sf * sf;
	s = sg * (1 - sl) + (1 - sf) * sl;
	c = (1 - sg) * (1 - sl) + sf * sl;
	w = Math.atan(Math.sqrt(s / c));
	r = Math.sqrt(s * c) / w;
	d = 2 * w * a;
	h1 = (3 * r - 1) / 2 / c;
	h2 = (3 * r + 1) / 2 / s;
	var num = d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg))
	// 换算单位
	if (num == undefined) {
		num = "0.0 m"
	};
	if (num < 1000) {
		num = (Math.round(num)).toFixed(1) + "m"
	} else if (num > 1000) {
		num = (Math.round(num / 100) / 10).toFixed(1) + "km"
	}
	return num
}
// px转upx
export const px2upx = function(n) {
	return n / (uni.upx2px(n) / n);
}

// 判断两时间段之间活动状态、判断活动还有多长时间开始、多长时间结束----添加定时器运行此方法可倒计时
// var startTime = new Date(item.startTime.replace(/-/g, '/')).getTime(); //转时间戳
// var closeTime = new Date(item.closeTime.replace(/-/g, '/')).getTime(); //转时间戳
// var djs = this.djsTime(startTime, closeTime);
export const djsTime = function(startTime, endTime) {
	var bbb = new Date().getTime(),
		leftTime = startTime - bbb,
		rightTime = endTime - bbb,
		djsTime = '',
		speed = 0,
		activityStatus = 0, //活动状态 1：未开始 2：进行中 3：已结束
		dd, hh, mm, ss;
	if (leftTime > 0) { //还未开始
		activityStatus = 1
		dd = Math.floor(leftTime / 1000 / 60 / 60 / 24);
		hh = Math.floor((leftTime / 1000 / 60 / 60) % 24) < 10 ? '0' + Math.floor((leftTime / 1000 / 60 / 60) %
			24) : Math.floor((leftTime / 1000 / 60 / 60) % 24);
		mm = Math.floor((leftTime / 1000 / 60) % 60) < 10 ? '0' + Math.floor((leftTime / 1000 / 60) % 60) : Math
			.floor((leftTime / 1000 / 60) % 60);
		ss = Math.floor((leftTime / 1000) % 60) < 10 ? '0' + Math.floor((leftTime / 1000) % 60) : Math.floor((
			leftTime / 1000) % 60);
		if (dd != 0) {
			djsTime = dd + "天 " + hh + ":" + mm + ":" + ss;
		} else {
			djsTime = hh + ":" + mm + ":" + ss;
		}
	} else if (leftTime <= 0) {
		if (rightTime > 0) { //进行中
			activityStatus = 2;
			speed = (1 - rightTime / (endTime - startTime)) * 100;
			dd = Math.floor(rightTime / 1000 / 60 / 60 / 24);
			hh = Math.floor((rightTime / 1000 / 60 / 60) % 24) < 10 ? '0' + Math.floor((rightTime / 1000 / 60 /
				60) % 24) : Math.floor((rightTime / 1000 / 60 / 60) % 24);
			mm = Math.floor((rightTime / 1000 / 60) % 60) < 10 ? '0' + Math.floor((rightTime / 1000 / 60) % 60) :
				Math.floor((rightTime / 1000 / 60) % 60);
			ss = Math.floor((rightTime / 1000) % 60) < 10 ? '0' + Math.floor((rightTime / 1000) % 60) : Math.floor((
				rightTime / 1000) % 60);
			if (dd != 0) {
				djsTime = dd + "天 " + hh + ":" + mm + ":" + ss;
			} else {
				djsTime = hh + ":" + mm + ":" + ss;
			}
		} else { //已结束
			speed = 100;
			djsTime = '已结束';
			activityStatus = 3;
		}
	}
	var item = {
		djsTime: djsTime, //距离当前时间差
		activityStatus: activityStatus, //活动状态 1：未开始 2：进行中 3：已结束
		speed: speed, //进度（单位%）
		dd: dd, //天
		hh: hh, //小时
		mm: mm, //分
		ss: ss, //秒
	}
	return item;
}

// 小程序获取定位权限判断
// isOpenSetting  默认false:不检验授权，true:检验授权后获取地址
function getMpLocation(successCallback, errCallback, isOpenSetting) {
	uni.getSetting({
		success: res => {
			if (res.authSetting['scope.userLocation'] || !isOpenSetting) {
				uni.getLocation({
					// #ifndef MP-ALIPAY
					type: 'gcj02',
					// #endif
					success(res) {
						console.log('successCallback')
						successCallback(res);
					},
					fail(err) {
						console.log("位置信息错误", err);
						errCallback("位置信息获取失败");
					}
				});
			} else {
				errCallback("“位置信息”未授权");
				isOpenSetting && uni.showModal({
					title: '提示',
					content: '请先在设置页面打开“位置信息”使用权限',
					confirmText: '去设置',
					cancelText: '再逛会',
					success: res => {
						if (res.confirm) {
							uni.openSetting();
						}
					}
				});
			}
		}
	});
}
// 获取地址信息
let locationAuthorize = true;
export const getAppLatLon = function(successCallback, errCallback, isOpenSetting) {
	const _this = this;
	// #ifdef MP-WEIXIN
	if (locationAuthorize && isOpenSetting) {
		uni.authorize({
			scope: 'scope.userLocation',
			success: () => {
				getMpLocation(successCallback, errCallback, isOpenSetting);
				locationAuthorize = false;
			},
			fail: () => {
				locationAuthorize = false;
			}
		});
	} else {
		getMpLocation(successCallback, errCallback, isOpenSetting);
	}
	// #endif
	// #ifdef MP-ALIPAY
	getMpLocation(successCallback, errCallback, false);
	// #endif
	// #ifdef H5
	uni.getLocation({
		type: 'gcj02',
		success(res) {
			console.log('successCallback')
			successCallback(res);
		},
		fail(err) {
			console.log("位置信息错误", err);
			errCallback("位置信息获取失败");
		}
	});
	// #endif
}

// 打开外链
export const openLink = function(href) {
	// #ifdef APP-PLUS
	plus.runtime.openURL(href)
	// #endif
	// #ifdef H5
	window.open(href)
	// #endif
	// #ifdef MP
	uni.setClipboardData({
		data: href,
		success: () => {
			uni.hideToast();
			this.$nextTick(() => {
				this.$u.toast('链接已复制，请在浏览器打开');
			})
		}
	});
	// #endif
}


export const getDateStr = (now) => {
	var year = now.getFullYear(); // 年
	var month = now.getMonth() + 1; // 月
	var day = now.getDate(); // 日
	if (day < 10) {
		day = '0' + day;
	}
	if (month < 10) {
		month = '0' + month;
	}
	return year + "-" + month + "-" + day;
}

//获取今天到本周末时间
export const getWeekTime = () => {
	var now = new Date();
	var nowDayOfWeek = now.getDay() == 0 ? 7 : (now.getDay() + 1);
	var startTime = getDateStr(now) + ' 00:00:00';
	var endTime = getDateStr(new Date(now.getTime() + nowDayOfWeek * 24 * 60 * 60 * 1000)) +
		' 23:59:59';
	let arr = [startTime, endTime]
	return arr
}
//获取今天时间
export const getTodayTime = () => {
	var now = new Date();
	var startTime = getDateStr(now) + ' 00:00:00'
	var endTime = getDateStr(now) + ' 23:59:59';
	let arr = [startTime, endTime]
	return arr
}
//获取 今天到7天前时间
export const getLastWeekTime = () => {
	var now = new Date();
	var startTime = getDateStr(new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)) + ' 00:00:00'
	var endTime = getDateStr(now) + ' 23:59:59';
	let arr = [startTime, endTime]
	return arr
}

//获取昨天时间
export const getYesterdayTime = () => {
	var now = new Date();
	var startTime = getDateStr(new Date(now.getTime() - 24 * 60 * 60 * 1000)) + ' 00:00:00'
	var endTime = getDateStr(new Date(now.getTime() - 24 * 60 * 60 * 1000)) + ' 23:59:59';
	let arr = [startTime, endTime]
	return arr
}
//获取30天时间
export const getMonthTime = () => {
	var now = new Date();
	var startTime = getDateStr(new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000)) + ' 00:00:00'
	var endTime = getDateStr(now) + ' 23:59:59';
	let arr = [startTime, endTime]
	return arr
}
export const goToPage = (url) => {
	if (!url) {
		return uni.showToast({
			title: '未获得跳转链接',
			icon: 'none'
		})
	}
	const pageNum = getCurrentPages()
	console.log('navigateTo pageNum: ', pageNum.length)
	if (pageNum.length > 9) {
		//当打开10个页面时，用redirectTo
		uni.redirectTo({
			url
		})
	} else {
		uni.navigateTo({
			url
		})
	}
}
/*函数节流*/
export function throttle(fn, interval) {
	var enterTime = 0; //触发的时间
	var gapTime = interval || 300; //间隔时间，如果interval不传，则默认300ms
	return function() {
		var context = this;
		var backTime = new Date(); //第一次函数return即触发的时间
		if (backTime - enterTime > gapTime) {
			fn.call(context, arguments);
			enterTime = backTime; //赋值给第一次触发的时间，这样就保存了第二次触发的时间
		}
	};
}

/*函数防抖*/
export function debounce(fn, interval) {
	var timer;
	var gapTime = interval || 200; //间隔时间，如果interval不传，则默认1000ms
	return function() {
		clearTimeout(timer);
		var context = this;
		var args = arguments; //保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
		timer = setTimeout(function() {
			fn.call(context, args);
		}, gapTime);
	};
}

export function toPrice(val) {
	if (!val) {
		val = 0;
	}
	return (val.toFixed(2))

};

export function parsePrice(val) {
	if (!val) {
		val = 0;
	}
	return val.toFixed(2).split(".");
}

/**
 * 判断字符串数组是否包含某字符串
 */
export function array_contain(array, obj) {
	for (var i = 0; i < array.length; i++) {
		if (array[i] == obj) //如果要求数据类型也一致，这里可使用恒等号===
			return true;
	}
	return false;
}

/**
 * 当前规格值是否可以选择  
 * 
 * 参数说明：
 * @param allProperties  ['颜色:金色;内存:64GB','颜色:金色;内存:256GB']
 * @param selectedPropObj {'颜色':'金色','内存':'64GB'}
 * @param propKeys ['颜色','内存']
 * @param key 颜色
 * @param item 金色
 * 
 * @return 0 可选但跟其他值不匹配  1 可选 
 */
export function props_contain(allProperties, selectedPropObj, key, item, propKeys) {
	var properties = "";
	selectedPropObj[key] = item;
	for (var j = 0; j < propKeys.length; j++) {
		properties += propKeys[j] + ":" + selectedPropObj[propKeys[j]] + ";";
	}
	properties = properties.substring(0, properties.length - 1);
	for (var i = 0; i < allProperties.length; i++) {
		if (properties == allProperties[i]) {
			return 1;
		}
	}
	return 0;
}

export function parseDiscount(discountRule) {
	if (discountRule == 0) {
		return '满额减';
	} else if (discountRule == 1) {
		return '满件减';
	} else if (discountRule == 2) {
		return '满额折';
	} else if (discountRule == 3) {
		return '满件折';
	} else {
		return '';
	}
}

export function parseDiscountMsg(discountRule, needAmount, discount) {
	if (discountRule == 0) {
		return '购满' + needAmount + '元减' + discount + '元';
	} else if (discountRule == 1) {
		return '购满' + needAmount + '件减' + discount + '元';
	} else if (discountRule == 2) {
		return '购满' + needAmount + '元打' + discount + '折';
	} else if (discountRule == 3) {
		return '购满' + needAmount + '件打' + discount + '折';
	} else {
		return '';
	}
}